<?php

namespace app\controller\admin\cms;

use app\BaseController;
use think\facade\Request;
use app\model\cms\CategoryModel;


class Category extends BaseController
{

    public function index()
    {

        $list = CategoryModel::get_list();

        return json($list);
    }

    public function single( )
    {

        $id = Request::param('id');
        $id = intval($id);
        // global $_GPC;
        // $id = $_GET['id'] ? intval($_GET['id']) : 0;
        $res = [
            'status' => 0
        ];
        if (!$id) {
            $res['status'] = 1;
            $res['message'] = '参数不合法';
        }
        $category = CategoryModel::single($id);
        $category['parent'] = CategoryModel::where('id',$category['parent_id'])->find();
        return json($category);
    }

    public function tree()
    {

        $tree = CategoryModel::children(0, true);

        return json($tree);
    }

    public function edit()
    {

        // global $_GPC;
        // $id = $_GET['id'] ? intval($_GET['id']) : 0;
        $id = Request::param( 'id' );
        $parent_id      = $_POST['parent_id'] ? intval($_POST['parent_id']) : 0;
        $name           = $_POST['name'];
        $sort_order     = $_POST['sort_order'] ? intval($_POST['sort_order']) : 0;
        $image          = $_POST['image'] ? $_POST['image'] : '';
        $is_recommend   = $_POST['is_recommend'] ? 1 : 0;

        // todo 获取 分类路径
        //        $path = CategoryModel::getParentsPath( $parent_id );
        //        $path = implode(',', $path['path_ids']);
        $data = [
            'name'          => $name,
            //            'path'          => $path,
            'sort_order'    => $sort_order,
            'parent_id'     => $parent_id,
            'image'         => $image,
            'is_recommend'  => $is_recommend,
        ];
        //todo 修改 category

        if ($id) {
            $ret = CategoryModel::update2($id, $data);
        } else {
            $id = $ret = CategoryModel::insert($data);
        }

        if (!$id) {
            $res['status'] = 1;
            $res['message'] = '保存失败';
            return json($res);
            die();
        }

        CategoryModel::setCategoryPath($id, $parent_id);

        $res['status'] = 0;
        $res['ret'] = $ret;
        return json($res);
    }

    public function delete()
    {

        // global $_GPC;
        $res = [
            'status' => 0,
        ];
        // $id = $_GPC['id'] ? intval($_GPC['id']) : 0;
        $id = Request::param( 'id' );
        $children = CategoryModel::children($id);

        if (empty($children)) {

            $res['ret'] = CategoryModel::delete2($id);
        } else {
            $res['status'] = 1;
            $res['message'] = '拥有子分类，无法删除';
        }

        return json($res);
    }
}
